<?php

namespace App\Http\Middleware;

use App\Models\Admin\Api;
use App\Models\Admin\Setting;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class ApiSignMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $signtoken = $request->header('Authorization');
        if(!$signtoken){
            return response()->json(['code'=>'601','data'=>'','msg'=>'非法请求']);
        }
        $pos = strpos($signtoken,".");
        if($pos){
            $auth['sign']=substr($signtoken,0,$pos);
            $auth['token']=substr($signtoken,$pos+1);
        }else{
            $auth['sign']=$signtoken;
        }
        $request->api_token = isset($auth['token'])?$auth['token']:'';
        //$_G['api_token'] = $request->api_token;
        $arr = $request->query();
        $arr['appkey']=Api::getappkey($arr['appid']);
        ksort($arr);
        $sign_params = self::_http_build_query($arr);
        $sign_params = md5($sign_params);
        $sign_params = md5($sign_params.$arr['nonce']);
        if($sign_params!=$auth['sign']){
            return response()->json(['code'=>'602','data'=>'','msg'=>'签名错误']);
        }
        $content_type = $request->header('content-type');
        if ($content_type == 'application/json') {
            $request->api_all = $request->json()->all();
            //var_dump($request->api_all);
        }
        Setting::getCache();
        return $next($request);
    }

    static function getCache($arr){
        Global $_G;
        $config = Cache::rememberForever('config', function () {
            return Setting::find('config')->value;
        });
        $_G = json_decode($config,true);
    }

    static function _http_build_query($arr){
        $narr=[];
        foreach ($arr as $key=>$val){
            $narr[]=$key.'='.$val;
        }
        $narr = implode('&',$narr);
        return $narr;
    }


}
